package com.touchwisdom.modular.common.system.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.touchwisdom.modular.common.dao.HibernateDao;
import com.touchwisdom.modular.common.service.CommonService;
import com.touchwisdom.modular.common.system.department.TDepartmentDao;
import com.touchwisdom.modular.util.config.Page;
import com.touchwisdom.modular.util.config.YesNoType;
import com.touchwisdom.modular.util.constant.StringConstUtil;

/**
 * 基于数据库的用户管理
 * 
 * @filename DefaultUserService.java
 * @author ggeagle
 * @date 2013-7-17 下午3:11:32
 */
@Service
@Transactional
public class UserService extends CommonService<TUser, String> {
	/**
	 * 用户数据访问DAO对象
	 */
	@Autowired
	public TUserDao userDAO;
	/**
	 * 部门信息DAO类
	 */
	@Autowired
	public TDepartmentDao departmentDao;

	public TUser acceptUser(TUser user) {
		if (user == null) {
			return null;
		}
		return this.userDAO.findUnique(Restrictions.eq("userName", user.getUserName()), Restrictions.eq("userPass", user.getUserPass()),
				Restrictions.eq("state", YesNoType.Y.name()));
	}

	/**
	 * 日志记录器
	 */
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 根据用户名和密码获取用户信息
	 * 
	 * @param name
	 *            用户名
	 * @param password
	 *            密码
	 * @return 根据用户和密码获取用户信息
	 */
	public TUser getUserByNamePass(String name, String password) {
		assert StringUtils.isNotBlank(name) : "用户名不能为空";
		assert StringUtils.isNotBlank(password) : "密码不能为空";
		logger.info("query user info by username and password : {} , {}", name, password);
		TUser user = this.userDAO.findUnique("from TUser u where u.userName =? and u.userPass = ? and u.state = ?", name, password, YesNoType.Y.name());
		return user;
	}

	/**
	 * 获取所有的用户信息
	 * 
	 * @return
	 */
	public Page<TUser> getUserList(Page<TUser> page, String hql, Object... args) {
		return this.userDAO.findPage(page, hql, args);
	}

	/**
	 * 删除用户
	 * 
	 * @param user
	 *            要删除的对象
	 */
	public void deleteUser(String idValue) {
		if (StringUtils.isNotBlank(idValue)) {
			String[] ids = StringUtils.split(idValue, StringConstUtil.COMMA);
			TUser user = null;
			for (String id : ids) {
				user = this.userDAO.get(id);
				user.setState(YesNoType.N.name());
				this.userDAO.save(user);
			}
		}
	}

	/**
	 * @author 周恪竭
	 * @param userName
	 *            用户名
	 * @return 根据用户名获取用户信息，进行模糊查询
	 */
	public TUser getUserByName(String userName) {
		TUser user = this.userDAO.findUnique("from TUser u where u.userName = ? and  u.state = ?", StringConstUtil.PERCENTAGE + userName + StringConstUtil.PERCENTAGE,
				YesNoType.Y.name());
		return user;
	}

	/**
	 * @author 周恪竭
	 * @param userName
	 *            用户名
	 * @return 根据用户名获取用户信息，进行模糊查询
	 */
	public List<TUser> queryUserByUserName(String userName) {
		List<TUser> userList = this.userDAO.find("from TUser u where u.userName like ? and  u.state = ?", StringConstUtil.PERCENTAGE + userName + StringConstUtil.PERCENTAGE,
				YesNoType.Y.name());
		return userList;
	}

	/**
	 * 按条件查询用户
	 * 
	 * @param key
	 *            属性
	 * @param value
	 *            值
	 * @return
	 */
	public List<TUser> getUsers(String key, String value) {
		List<TUser> tList = new ArrayList<TUser>();
		tList = this.userDAO.find(Restrictions.eq(key, value));
		return tList;
	}

	/**
	 * 修改用户密码
	 * 
	 * @param userId
	 */
	public boolean updatePassword(String userId, String oldPass, String newPassword) {
		assert StringUtils.isNotBlank(userId);
		assert StringUtils.isNotBlank(newPassword);
		boolean result = false;
		// 根据用户id获取用户信息
		TUser user = userDAO.get(userId);
		if (StringUtils.equals(user.getUserPass(), oldPass)) {
			user.setUserPass(newPassword);
			// 更新用户信息
			userDAO.save(user);
			result = true;
		}
		return result;
	}

	/**
	 * 如果有用户。返回true 否则返回false
	 * 
	 * @param userName
	 * @return
	 */

	/**
	 * 更新密码
	 */
	public String resetPassword(String id, String password) {
		final String hql = "update TUser u set u.userPass = :password where u.id=:id";
		Query query = this.userDAO.getSession().createQuery(hql);
		query.setParameter("password", password);
		query.setParameter("id", id);
		query.executeUpdate();
		return this.userDAO.get(id).getRealName();
	}

	public TUser login(String userName, String password) {
		TUser user = userDAO.findUnique(Restrictions.eq("userName", userName), Restrictions.eq("userPass", password), Restrictions.eq("state", YesNoType.Y.name()));
		return user;
	}

	/**
	 * 查询分类外部人员
	 * 
	 * @param page
	 * @param sortId
	 * @return
	 */
	public Page<TUser> querySortingExternalPersonnel(Page<TUser> page, String sortId, String departmentId, String userName) {
		String hql = "FROM TUser WHERE id NOT IN (SELECT userId FROM ManualSortingPermissionEntity WHERE manualSortingId='" + sortId + "') AND state = '" + YesNoType.Y.name()
				+ "'";
		if (departmentId != null && !departmentId.equals("")) {

		}
		if (userName != null && !userName.equals("")) {
			hql += "  AND realName like '%" + userName + "%'   ";
		}
		List<TUser> userList = userDAO.getUserList(hql, page.getPageSize(), (page.getPageNo() - 1) * page.getPageSize());
		page.setTotalCount(userDAO.find(hql).size());
		page.setResult(userList);
		return page;
	}

	/**
	 * 查询分类内部人员
	 * 
	 * @param page
	 * @param sortId
	 * @return
	 */
	public Page<TUser> querySortingInternalPersonnel(Page<TUser> page, String sortId, String departmentId, String userName) {
		String hql = "FROM TUser WHERE id IN (SELECT userId FROM ManualSortingPermissionEntity WHERE manualSortingId='" + sortId + "') and state = " + YesNoType.Y.name();
		if (departmentId != null && !departmentId.equals("")) {

		}
		if (userName != null && !userName.equals("")) {
			hql += "  AND realName like '%" + userName + "%'   ";
		}
		List<TUser> userList = userDAO.getUserList(hql, page.getPageSize(), (page.getPageNo() - 1) * page.getPageSize());
		page.setTotalCount(userDAO.find(hql).size());
		page.setResult(userList);
		return page;
	}

	@Override
	public TUser getEntity(String id) {
		return this.userDAO.get(id);
	}

	/**
	 * 根据用户名检测用户是否存在
	 * 
	 * @param userName
	 * @return
	 */
	public boolean checkNotExistByUserName(String userName) {
		TUser user = null;
		if (StringUtils.isNotBlank(userName)) {
			user = this.userDAO.findUnique(Restrictions.eq(TUser.PROPERTY_USER_NAME, userName), Restrictions.eq(TUser.PROPERTY_STATE, YesNoType.Y.name()));
		}
		return user == null;
	}

	/**
	 * 根据手机信息检测用户是否存在
	 * 
	 * @param phone
	 * @return
	 */
	public TUser checkUserByMobile(String mobile) {
		TUser user = null;
		if (StringUtils.isNotBlank(mobile)) {
			user = this.userDAO.findUnique(Restrictions.eq(TUser.PROPERTY_MOBILE, mobile), Restrictions.eq(TUser.PROPERTY_STATE, YesNoType.Y.name()));
		}
		return user;
	}

	/**
	 * 根据邮箱信息检察用户是否存在
	 * 
	 * @param email
	 * @return
	 */
	public TUser checkUserByEmail(String email) {
		TUser user = null;
		if (StringUtils.isNotBlank(email)) {
			user = this.userDAO.findUnique(Restrictions.eq(TUser.PROPERTY_EMAIL, email), Restrictions.eq(TUser.PROPERTY_STATE, YesNoType.Y.name()));
		}
		return user;
	}

	@Override
	protected HibernateDao<TUser, String> getHibernateDao() {
		return this.userDAO;
	}

	public boolean checkExist(TUser user) {
		List<TUser> find = this.userDAO.find(Restrictions.eq("userName", user.getUserName()), Restrictions.eq("state", YesNoType.Y.name()));
		return find != null && find.size() > 0;
	}
}